<template>
  <div>
    <div style="font-size:16px;font-weight: 600;"> <el-radio></el-radio>渠道来源管理</div>
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px;">
      <el-form-item>
        <el-select placeholder="请选择展会" v-model="state.dataForm.tid" filterable clearable>
          <el-option v-for="option in templates" :key="option.id" :label="option.template"
            :value="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select placeholder="请选择分组" v-model="state.dataForm.gid" clearable>
          <el-option v-for="option in groupList" :key="option.id" :label="option.groupName"
            :value="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input style="width: 200px;" placeholder="备注" clearable v-model="state.dataForm.remark"></el-input>
      </el-form-item>
      <!--查询 -->
      <el-form-item v-if="state.hasPermission('noc:nocly:info')">
        <el-button @click="query()">{{ $t("query") }}</el-button>
      </el-form-item>
      <!--新增 -->
      <el-form-item v-if="state.hasPermission('noc:nocly:save')">
        <el-button type="primary" @click="addOrUpdateHandle('new')">{{ $t("add")
        }}</el-button>
      </el-form-item>
      <!-- 修改 -->
      <el-form-item v-if="state.hasPermission('noc:nocly:update')">
        <el-button type="info" @click="addOrUpdateHandle('edit')" :disabled="state.single">{{ $t("修改")
        }}</el-button>
      </el-form-item>
      <!-- 删除 -->
      <el-form-item v-if="state.hasPermission('noc:nocly:delete')">
        <el-button type="danger" @click="state.deleteHandle()" :disabled="state.multiple">{{ $t("deleteBatch")
        }}</el-button>
      </el-form-item>
      <!-- 批量修改分组 -->
      <el-form-item v-if="state.hasPermission('noc:nocly:updategroup')">
        <el-button type="primary" @click="groupHandle()" :disabled="state.multiple">批量修改分组</el-button>
      </el-form-item>
      <el-table fit :header-cell-style="{ 'background': '#eef1f6', 'color': '#1f2d3d', 'border-color': '#dfe6ec' }"
        v-loading="state.dataListLoading" :data="state.dataList" border
        @selection-change="state.dataListSelectionChangeHandle" style="width: 100%;margin-top: 15px">
        <el-table-column type="selection"></el-table-column>
        <el-table-column align="center" prop="id" label="id" show-overflow-tooltip width="100"></el-table-column>
        <el-table-column align="center" prop="tname" label="展会名称" show-overflow-tooltip width="240"></el-table-column>
        <el-table-column align="center" prop="gname" label="组名" show-overflow-tooltip width="120"></el-table-column>
        <el-table-column align="center" prop="ly" label="来源" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column align="center" prop="remark" label="备注" show-overflow-tooltip width="120"></el-table-column>
        <el-table-column align="center" prop="isVip" label="预登记" show-overflow-tooltip>
          <template v-slot="{ row }">
            <el-tag v-if="row.isVip == 1" size="small" type="success">是</el-tag>
            <el-tag v-else size="small" type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="url" label="链接地址" show-overflow-tooltip width="400">
          <template #default="scope">
            <div class="url-container">
              <span class="url-text">{{ scope.row.url ? scope.row.url.replace('amp;', '') : '' }}</span>
              <el-icon class="copy-icon" v-if="scope.row.url" @click="copyUrl(scope.row.url)">
                <CopyDocument />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="shortUrl" label="短链接" show-overflow-tooltip width="200">
          <template #default="scope">
            <div class="url-container2">
              <span class="url-text2">{{ scope.row.shortUrl }}</span>
              <el-icon class="copy-icon2" v-if="scope.row.shortUrl" @click="copyUrl2(scope.row.shortUrl)">
                <CopyDocument />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="" label="团队链接" show-overflow-tooltip width="400" v-if="state.hasPermission('noc:ly:teamlink')">
          <template #default="scope">
            <div class="url-container2"
              v-if="scope.row.ly !== 'xianchang' && scope.row.url && scope.row.url.includes('https://preg.jinnoc.com/h5/index')">
              <span class="url-text">
                {{ scope.row.url.replace('amp;', '').replace('https://preg.jinnoc.com/h5/index',
                'https://team.jinnoc.com/login') }}
              </span>
              <el-icon class="copy-icon" @click="copyUrl3(scope.row.url)">
                <CopyDocument />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="startTime" label="开始时间" show-overflow-tooltip
          width="200"></el-table-column>
        <el-table-column align="center" prop="endTime" label="到期时间" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column align="center" prop="creator" label="创建人" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" show-overflow-tooltip
          width="200"></el-table-column>
        <el-table-column align="center" prop="updator" label="更新人" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="updateTime" label="更新时间" show-overflow-tooltip width="200"></el-table-column>
      </el-table>
    </el-form>
    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
      :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
      @current-change="state.pageCurrentChangeHandle"> </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="refreshDataList"></add-or-update>
    <!-- 批量修改分组 -->
    <group :key="generateGroupKey" ref="groupRef" @refreshDataList="refreshDataList"></group>
  </div>
</template>
<script lang="ts" setup>
import useView from "@/hooks/useView";
import { computed, nextTick, reactive, ref, toRefs, watch } from "vue";
import AddOrUpdate from "./nocly-add-or-update.vue";
import group from "./noc-promotiongroup.vue";
import { useRouter } from 'vue-router'
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from 'element-plus'
import Template from "@/views/devtools/template.vue";

const view = reactive({
  getDataListURL: 'noc/nocly/page',
  createdIsNeed: true,
  getDataListIsPage: true,
  deleteURL: "noc/nocly/delete",
  deleteIsBatch: true,
  dataForm: {
    tid: '', //展会名称
    gid: '', //分组
    id: "",
    remark: "",
  },
  showList: true,
  showGroup: true,
  title: null as any,
  nocLy: {},
  templates: [],
  templateId: "",
  groupList: [],
  groupId: null as any,
  url: "",
  groupIds: "",

});

const init = () => {
  getGroup();
  getTemplates();
};

const state = reactive({ ...useView(view), ...toRefs(view) });
const addKey = ref(0);
const ida = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (operationType: 'new' | 'edit', id?: number) => {
  addKey.value++;
  if (operationType === 'new') {
    // 新增逻辑，这里不需要传递已有的id，直接进行新增相关初始化等操作
    nextTick(() => {
      addOrUpdateRef.value.init();
    });
  } else if (operationType === 'edit') {
    if (state.dataListSelections) {
      if (Object.keys(state.dataListSelections).length === 0) {
        if (id) {
          // 若单独点击编辑按钮且传递了id，直接使用该id进行编辑初始化
          nextTick(() => {
            addOrUpdateRef.value.init(id);
          });
        }
      } else {
        ida.value = state.dataListSelections[0].id;
        nextTick(() => {
          addOrUpdateRef.value.init(Number(ida.value));
        });
      }
    }
  }
};

//批量修改分组
const groupKey = ref([] as any[]);
const groupRef = ref();
const generateGroupKey = computed(() => {
  return groupKey.value.join('-'); // 将数组元素连接成一个字符串作为唯一标识
});

const groupHandle = () => {
  groupKey.value = []; // 清空数组
  if (state.dataListSelections) {
    if (Object.keys(state.dataListSelections).length === 0) {
      return;
    } else {
      //获取选中的id
      for (let i = 0; i < state.dataListSelections.length; i++) {
        groupKey.value.push(state.dataListSelections[i].id);
      }
      nextTick(() => {
        groupRef.value.init(groupKey.value);
      });
    }
  }
}

//刷新数据
const refreshDataList = () => {
  state.refreshDataList();
};

//展会名称列表
const templates = ref<any[]>([]);
const getTemplates = () => {
  baseService.get('/crm/noctemplate/list2', { validStartTimeFlag: true, limit: 300 }).then((res) => {
    if (res.code == 0) {
      //刷新
      templates.value = res.data;
    }
  });
};

//分组列表
const groupList = ref<any[]>([]);
const getGroup = () => {
  baseService.post('/noc/noclygroup/list', { limit: 100 }).then((res) => {
    if (res.code == 0) {
      //刷新
      groupList.value = res.data.list;
    }
  });
};

//复制链接地址
const copyUrl = async (text: string) => {
  try {
    text = text ? text.replace('amp;', '') : '';
    await navigator.clipboard.writeText(text);
    // 显示成功提示消息
    ElMessage.success('复制成功');
  } catch (err) {
    ElMessage.error('复制失败');
  }
};

//复制短链接
const copyUrl2 = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    // 显示成功提示消息
    ElMessage.success('复制成功');
  } catch (err) {
    ElMessage.error('复制失败');
  }
};

//复制团队链接
const copyUrl3 = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    // 显示成功提示消息
    ElMessage.success('复制成功');
  } catch (err) {
    ElMessage.error('复制失败');
  }
};

//查询
const query = () => {
  //校验展会必须选择
  // if (state.dataForm.tid == '') {
  //   ElMessage.error('展会名称必须选择');
  //   return;
  // }

  state.getDataList();
};




init();
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
  white-space: nowrap;
}

.url-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.url-text {
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.copy-icon {
  cursor: pointer;
}

.url-container2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.url-text2 {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.copy-icon2 {
  cursor: pointer;
}
</style>
